package earogya.pharmacy.patient;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import earogya.pharmacy.patient.Dispenced_Treatments;
import earogya.pharmacy.patient.Requested_Treatments;
import earogya.util.PatientHibernateUtil;

/*Class PatientHibernateManager
 * Save an object to database using hibernate
 * 
 * 
 * */
public class PatientHibernateManager {

	public PatientHibernateManager() {
	}

	public int saveObject(Object obj) throws HibernateException {
		Integer id = 0;
		try {
		
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();
		
			session.beginTransaction();
			id = (Integer) session.save(obj);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			throw e;
		}
		return id;
	}

	public int queryValuesFromDatabase(Object[][] fieldsAndValues,
			String required_field, String table) {
		int value = -1;
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();

		session.beginTransaction();
		SQLQuery query = session.createSQLQuery(this.buildSelectQuery(
				fieldsAndValues, required_field, table));
		query.setMaxResults(1);
		List list = query.list();
		if (list.size() == 1) {
			value = (Integer) list.get(0);
		}
		return value;
	}

	public List queryAllFieldsFromDatabase(Object[][] fieldsAndValues,
			String table) {
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();
		List list = null;
		session.beginTransaction();
		Query query = session.createQuery(this.buildSelectAllQuery(
				fieldsAndValues, table));
		list = query.list();

		return list;
	}

	public List queryValueListFromDatabase(Object[][] fieldsAndValues,
			String required_field, String table) {
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();
		List list = null;
		session.beginTransaction();
		SQLQuery query = session.createSQLQuery(this.buildSelectQuery(
				fieldsAndValues, required_field, table));
		list = query.list();

		return list;
	}

	public List queryValueListFromDatabase(Object[][] fieldsAndValues,
			String[] required_field, String className, String objectName) {
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();
		List list = null;
		// try{
		session.beginTransaction();
		Query query = session.createQuery(this.buildSelectQuery(
				fieldsAndValues, required_field, className, objectName));
		list = query.list();
		return list;
	}

	private String buildSelectQuery(Object[][] fieldsAndValues,
			String[] required_field, String className, String objectName) {
		StringBuilder builder = new StringBuilder();
		builder.append("SELECT ");
		for (int i = 0; i < required_field.length; i++) {
			if (i < required_field.length - 1) {
				builder.append(objectName + "." + required_field[i] + ", ");
			} else {
				builder.append(objectName + "." + required_field[i] + " FROM "
						+ className + " AS " + objectName + " WHERE ");
			}
		}
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(objectName + "." + fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(objectName + "." + fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	private String buildSelectQuery(Object[][] fieldsAndValues,
			String required_field, String table) {
		StringBuilder builder = new StringBuilder();
		builder.append("SELECT " + required_field + " FROM " + table
				+ " WHERE ");
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	private String buildSelectAllQuery(Object[][] fieldsAndValues, String table) {
		StringBuilder builder = new StringBuilder();
		builder.append("SELECT {patient.*} FROM " + table + " WHERE ");
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	private String buildDeleteQuery(Object[][] fieldsAndValues, String table) {
		StringBuilder builder = new StringBuilder();
		builder.append("DELETE FROM " + table + " WHERE ");
		for (int i = 0; i < fieldsAndValues.length; i++) {
			if (i < fieldsAndValues.length - 1) {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "' AND ");
			} else {
				builder.append(fieldsAndValues[i][0] + "='"
						+ fieldsAndValues[i][1] + "'");
			}
		}
		return builder.toString();
	}

	public Boolean deleteEntry(Object[][] fieldsAndValues, String table) {
		Boolean isSuccesful = false;
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();
		try {
			session.beginTransaction();
			SQLQuery query = session.createSQLQuery(this.buildDeleteQuery(
					fieldsAndValues, table));
			int no_of_rows = query.executeUpdate();
			if (no_of_rows > 0) {
				isSuccesful = true;
			}
		} catch (HibernateException e) {
			isSuccesful = false;
		}
		return isSuccesful;
	}

	public Boolean updateDispence(Dispenced_Treatments treat) {
		Boolean isSuccessful;
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();
		try {
			session.beginTransaction();
			Dispenced_Treatments treat1 = (Dispenced_Treatments) session.get(
					Dispenced_Treatments.class, treat.getDispenceId());
			if (treat.getDrugId() == 0) {
			} else {
				treat1.setDrugId(treat.getDrugId());
			}
			if (treat.getPatientId() == 0) {
			} else {
				treat1.setPatientId(treat.getPatientId());
			}
			if (treat.getNoOfIssues() == 0) {
			} else {
				treat1.setNoOfIssues(treat.getNoOfIssues());
			}
			if (treat.getDosage() == null) {
			} else {
				treat1.setDosage(treat.getDosage());
			}
			if (treat.getDispencedQuantity() == 0) {
			} else {
				treat1.setDispencedQuantity(treat.getDispencedQuantity());
			}
			if (treat.getDispenceUnits() == null) {
			} else {
				treat1.setDispenceUnits(treat.getDispenceUnits());
			}
			if (treat.getPrescriptionNo() == 0) {
			} else {
				treat1.setPrescriptionNo(treat.getPrescriptionNo());
			}
			if (treat.getDispencedById() == 0) {
			} else {
				treat1.setDispencedById(treat.getDispencedById());
			}
			if (treat.getDispenceDate() == null) {
			} else {
				treat1.setDispenceDate(treat.getDispenceDate());
			}
			if (treat.getDispenceTime() == null) {
			} else {
				treat1.setDispenceTime(treat.getDispenceTime());
			}

			session.update(treat1);
			session.getTransaction().commit();
			isSuccessful = true;
		} catch (HibernateException e) {
			isSuccessful = false;
			throw e;
		}
		return isSuccessful;
	}

	public Boolean updateRequestTreatment(Requested_Treatments requestTreat) {
		Boolean isSuccessful;
		Session session = PatientHibernateUtil.getSessionFactory()
				.getCurrentSession();
		try {
			session.beginTransaction();
			Requested_Treatments requestTreat1 = (Requested_Treatments) session
					.get(Requested_Treatments.class,
							requestTreat.getRequestId());
			if (requestTreat.getPatientId() == 0) {
			} else {
				requestTreat1.setPatientId(requestTreat.getPatientId());
			}
			if (requestTreat.getDrugId() == 0) {
			} else {
				requestTreat1.setDrugId(requestTreat.getDrugId());
			}
			if (requestTreat.getDosage() == null) {
			} else {
				requestTreat1.setDosage(requestTreat.getDosage());
			}
			if (requestTreat.getQuantity() == 0) {
			} else {
				requestTreat1.setQuantity(requestTreat.getQuantity());
			}
			if (requestTreat.getPrescribedByID() == 0) {
			} else {
				requestTreat1.setPrescribedByID(requestTreat
						.getPrescribedByID());
			}
			if (requestTreat.getPrescriptionNo() == 0) {
			} else {
				requestTreat1.setPrescriptionNo(requestTreat
						.getPrescriptionNo());
			}
			if (requestTreat.getAllowSubstitutes() == false) {
			} else {
				requestTreat1.setAllowSubstitutes(requestTreat
						.getAllowSubstitutes());
			}
			if (requestTreat.getMaxAmount() == 0) {
			} else {
				requestTreat1.setMaxAmount(requestTreat.getMaxAmount());
			}
			if (requestTreat.getMinAmount() == 0) {
			} else {
				requestTreat1.setMinAmount(requestTreat.getMinAmount());
			}
			if (requestTreat.getAmountUnits() == null) {
			} else {
				requestTreat1.setAmountUnits(requestTreat.getAmountUnits());
			}
			if (requestTreat.getRequestDate() == null) {
			} else {
				requestTreat1.setRequestDate(requestTreat.getRequestDate());
			}
			if (requestTreat.getRequestTime() == null) {
			} else {
				requestTreat1.setRequestTime(requestTreat.getRequestTime());
			}

			session.update(requestTreat1);
			session.getTransaction().commit();
			isSuccessful = true;
		} catch (HibernateException e) {
			isSuccessful = false;
			throw e;
		}
		return isSuccessful;
	}
	
	public List Query(String query){
		List list = null;
		Session session = PatientHibernateUtil.getSessionFactory()
		.getCurrentSession();
		session.beginTransaction();
		list =session.createQuery(query).list();  //.createSQLQuery(query).list();
		return list;
	}
}
